import 'package:dio/dio.dart';
import '../config/api_config.dart';

class WeatherService {
  final Dio _dio = Dio();

  // 使用免费的OpenWeatherMap API
  // 注册地址: https://openweathermap.org/api
  // 免费版本每分钟60次调用，每月100万次调用
  static const String _apiKey = ApiConfig.openWeatherMapApiKey;
  static const String _baseUrl = 'https://api.openweathermap.org/data/2.5';

  WeatherService() {
    _dio.options.baseUrl = _baseUrl;
    _dio.options.connectTimeout = const Duration(seconds: 10);
    _dio.options.receiveTimeout = const Duration(seconds: 10);
  }

  /// 根据经纬度获取天气信息
  Future<Map<String, dynamic>> getWeatherByCoordinates(
    double latitude, 
    double longitude
  ) async {
    try {
      // 检查API密钥是否配置
      if (_apiKey.isEmpty) {
        return _getDefaultWeather();
      }

      final response = await _dio.get('/weather', queryParameters: {
        'lat': latitude,
        'lon': longitude,
        'appid': _apiKey,
        'units': 'metric', // 使用摄氏度
        'lang': 'zh_cn', // 中文描述
      });

      if (response.statusCode == 200) {
        final data = response.data;
        
        // 解析天气数据
        final weather = data['weather'][0];
        final main = data['main'];
        
        String weatherDesc = _getWeatherDescription(weather['id']);
        String weatherIcon = _getWeatherIcon(weather['id']);
        
        final result = {
          'success': true,
          'temperature': main['temp'].round(),
          'description': weatherDesc,
          'icon': weatherIcon,
          'humidity': main['humidity'],
          'pressure': main['pressure'],
          'windSpeed': data['wind']?['speed'] ?? 0,
        };
        
        return result;
      } else {
        return _getDefaultWeather();
      }
    } catch (e) {
      return _getDefaultWeather();
    }
  }

  /// 根据城市名获取天气信息
  Future<Map<String, dynamic>> getWeatherByCity(String cityName) async {
    try {
      final response = await _dio.get('/weather', queryParameters: {
        'q': cityName,
        'appid': _apiKey,
        'units': 'metric',
        'lang': 'zh_cn',
      });

      if (response.statusCode == 200) {
        final data = response.data;
        final weather = data['weather'][0];
        final main = data['main'];
        
        String weatherDesc = _getWeatherDescription(weather['id']);
        String weatherIcon = _getWeatherIcon(weather['id']);
        
        final result = {
          'success': true,
          'temperature': main['temp'].round(),
          'description': weatherDesc,
          'icon': weatherIcon,
          'humidity': main['humidity'],
          'pressure': main['pressure'],
          'windSpeed': data['wind']?['speed'] ?? 0,
        };
        
        return result;
      } else {
        return _getDefaultWeather();
      }
    } catch (e) {
      return _getDefaultWeather();
    }
  }

  /// 获取默认天气信息
  Map<String, dynamic> _getDefaultWeather() {
    return {
      'success': false,
      'temperature': 22,
      'description': '晴',
      'icon': '☀️',
      'humidity': 60,
      'pressure': 1013,
      'windSpeed': 0,
    };
  }

  /// 根据天气代码获取中文描述
  String _getWeatherDescription(int weatherId) {
    if (weatherId >= 200 && weatherId < 300) {
      return '雷雨';
    } else if (weatherId >= 300 && weatherId < 400) {
      return '小雨';
    } else if (weatherId >= 500 && weatherId < 600) {
      return '雨';
    } else if (weatherId >= 600 && weatherId < 700) {
      return '雪';
    } else if (weatherId >= 700 && weatherId < 800) {
      return '雾';
    } else if (weatherId == 800) {
      return '晴';
    } else if (weatherId > 800) {
      return '多云';
    } else {
      return '晴';
    }
  }

  /// 根据天气代码获取图标
  String _getWeatherIcon(int weatherId) {
    if (weatherId >= 200 && weatherId < 300) {
      return '⛈️';
    } else if (weatherId >= 300 && weatherId < 400) {
      return '🌦️';
    } else if (weatherId >= 500 && weatherId < 600) {
      return '🌧️';
    } else if (weatherId >= 600 && weatherId < 700) {
      return '❄️';
    } else if (weatherId >= 700 && weatherId < 800) {
      return '🌫️';
    } else if (weatherId == 800) {
      return '☀️';
    } else if (weatherId > 800) {
      return '☁️';
    } else {
      return '☀️';
    }
  }
}